const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const fs = require('fs');
const path = require('path');

const app = express();
const PORT = 3002; // 更改端口为3002，避免冲突
const dataFilePath = path.join(__dirname, 'data.json');

// 中间件
app.use(cors());
app.use(bodyParser.json());

// 在开发环境中不提供前端静态文件服务
// 只在生产环境中提供前端静态文件服务
const isDevelopment = process.env.NODE_ENV === 'development';
console.log('NODE_ENV:', process.env.NODE_ENV);
console.log('isDevelopment:', isDevelopment);

if (!isDevelopment) {
  // 提供前端静态文件服务
  const frontendDistPath = path.join(__dirname, '..', 'frontend', 'dist');
  if (fs.existsSync(frontendDistPath)) {
    console.log('Serving frontend static files from:', frontendDistPath);
    app.use(express.static(frontendDistPath));
    
    // 处理前端路由，将所有未匹配的路由都返回 index.html
    app.get('*', (req, res) => {
      res.sendFile(path.join(frontendDistPath, 'index.html'));
    });
  } else {
    console.log('Frontend dist directory not found');
    // 如果没有前端构建文件，提供一个简单的根路径响应
    app.get('/', (req, res) => {
      res.send(`
        <h1>新选车系统后端服务</h1>
        <p>服务正在运行中...</p>
        <p>API 端点:</p>
        <ul>
          <li><a href="/api/brands">/api/brands</a> - 获取所有品牌信息</li>
        </ul>
      `);
    });
  }
} else {
  console.log('Development mode: Not serving frontend static files');
  // 开发环境下的根路径响应
  app.get('/', (req, res) => {
    res.send(`
      <h1>新选车系统后端服务 (开发模式)</h1>
      <p>服务正在运行中...</p>
      <p>API 端点:</p>
      <ul>
        <li><a href="/api/brands">/api/brands</a> - 获取所有品牌信息</li>
      </ul>
    `);
  });
}

// 确保data.json文件存在
function ensureDataFile() {
  if (!fs.existsSync(dataFilePath)) {
    // 初始化为一对多结构
    fs.writeFileSync(dataFilePath, JSON.stringify({
      brands: []
    }));
  }
}

// 读取数据
function readData() {
  ensureDataFile();
  const data = fs.readFileSync(dataFilePath);
  return JSON.parse(data);
}

// 写入数据
function writeData(data) {
  fs.writeFileSync(dataFilePath, JSON.stringify(data, null, 2));
}

// 获取所有品牌信息
app.get('/api/brands', (req, res) => {
  try {
    const data = readData();
    res.json(data.brands);
  } catch (error) {
    res.status(500).json({ error: 'Failed to read data' });
  }
});

// 根据品牌名称获取品牌详细信息（包括所有配置）
app.get('/api/brands/:brandName', (req, res) => {
  try {
    const data = readData();
    const brandName = req.params.brandName;
    const brand = data.brands.find(b => b.name === brandName);
    if (brand) {
      res.json(brand);
    } else {
      res.status(404).json({ error: 'Brand not found' });
    }
  } catch (error) {
    res.status(500).json({ error: 'Failed to read data' });
  }
});

// 根据品牌名称和配置名称获取特定配置的详细信息
app.get('/api/brands/:brandName/configs/:configName', (req, res) => {
  try {
    const data = readData();
    const brandName = req.params.brandName;
    const configName = req.params.configName;
    
    const brand = data.brands.find(b => b.name === brandName);
    if (brand) {
      const config = brand.configs.find(c => c.name === configName);
      if (config) {
        res.json(config);
      } else {
        res.status(404).json({ error: 'Config not found' });
      }
    } else {
      res.status(404).json({ error: 'Brand not found' });
    }
  } catch (error) {
    res.status(500).json({ error: 'Failed to read data' });
  }
});

// 创建新品牌
app.post('/api/brands', (req, res) => {
  try {
    const data = readData();
    const newBrand = {
      id: data.brands.length > 0 ? Math.max(...data.brands.map(b => b.id)) + 1 : 1,
      name: req.body.name,
      configs: []
    };
    data.brands.push(newBrand);
    writeData(data);
    res.status(201).json(newBrand);
  } catch (error) {
    res.status(500).json({ error: 'Failed to write data' });
  }
});

// 为品牌添加新配置
app.post('/api/brands/:brandName/configs', (req, res) => {
  try {
    const data = readData();
    const brandName = req.params.brandName;
    const brand = data.brands.find(b => b.name === brandName);
    
    if (brand) {
      const newConfig = {
        id: brand.configs.length > 0 ? Math.max(...brand.configs.map(c => c.id)) + 1 : 1,
        name: req.body.name, // 配置名称
        guidePrice: req.body.guidePrice, // 指导价
        recentDiscount: req.body.recentDiscount, // 近期优惠
        nakedCarPrice: req.body.nakedCarPrice, // 裸车
        insuranceFee: req.body.insuranceFee, // 险费
        purchaseTax: req.body.purchaseTax, // 购置
        licenseFee: req.body.licenseFee, // 上牌
        fullPrice: req.body.fullPrice, // 全款落地
        downPayment: req.body.downPayment, // 首付
        loanAmount: req.body.loanAmount, // 贷款金额
        loanTerm: req.body.loanTerm, // 年期
        interestRate: req.body.interestRate, // 年利率
        monthlyPayment: req.body.monthlyPayment, // 每月还款额
        totalInterest: req.body.totalInterest // 总利息
      };
      brand.configs.push(newConfig);
      writeData(data);
      res.status(201).json(newConfig);
    } else {
      res.status(404).json({ error: 'Brand not found' });
    }
  } catch (error) {
    res.status(500).json({ error: 'Failed to write data' });
  }
});

// 更新品牌配置
app.put('/api/brands/:brandName/configs/:configName', (req, res) => {
  try {
    const data = readData();
    const brandName = req.params.brandName;
    const configName = req.params.configName;
    
    const brand = data.brands.find(b => b.name === brandName);
    if (brand) {
      const configIndex = brand.configs.findIndex(c => c.name === configName);
      if (configIndex !== -1) {
        const updatedConfig = {
          id: brand.configs[configIndex].id,
          name: req.body.name, // 配置名称
          guidePrice: req.body.guidePrice, // 指导价
          recentDiscount: req.body.recentDiscount, // 近期优惠
          nakedCarPrice: req.body.nakedCarPrice, // 裸车
          insuranceFee: req.body.insuranceFee, // 险费
          purchaseTax: req.body.purchaseTax, // 购置
          licenseFee: req.body.licenseFee, // 上牌
          fullPrice: req.body.fullPrice, // 全款落地
          downPayment: req.body.downPayment, // 首付
          loanAmount: req.body.loanAmount, // 贷款金额
          loanTerm: req.body.loanTerm, // 年期
          interestRate: req.body.interestRate, // 年利率
          monthlyPayment: req.body.monthlyPayment, // 每月还款额
          totalInterest: req.body.totalInterest // 总利息
        };
        brand.configs[configIndex] = updatedConfig;
        writeData(data);
        res.json(updatedConfig);
      } else {
        res.status(404).json({ error: 'Config not found' });
      }
    } else {
      res.status(404).json({ error: 'Brand not found' });
    }
  } catch (error) {
    res.status(500).json({ error: 'Failed to update data' });
  }
});

// 删除品牌配置
app.delete('/api/brands/:brandName/configs/:configName', (req, res) => {
  try {
    const data = readData();
    const brandName = req.params.brandName;
    const configName = req.params.configName;
    
    const brand = data.brands.find(b => b.name === brandName);
    if (brand) {
      const configIndex = brand.configs.findIndex(c => c.name === configName);
      if (configIndex !== -1) {
        brand.configs.splice(configIndex, 1);
        writeData(data);
        res.status(204).send();
      } else {
        res.status(404).json({ error: 'Config not found' });
      }
    } else {
      res.status(404).json({ error: 'Brand not found' });
    }
  } catch (error) {
    res.status(500).json({ error: 'Failed to delete data' });
  }
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});